<template>
  <div class="bill-management">
    <h2>账单管理</h2>
    
    <!-- 添加账单表单 -->
    <div class="add-bill-form">
      <h3>添加新账单</h3>
      <div class="form-group">
        <label>类型：</label>
        <select v-model="newBill.type">
          <option value="income">收入</option>
          <option value="expense">支出</option>
        </select>
      </div>
      <div class="form-group">
        <label>金额：</label>
        <input type="number" v-model.number="newBill.amount" placeholder="请输入金额">
      </div>
      <div class="form-group">
        <label>类别：</label>
        <input type="text" v-model="newBill.category" placeholder="例如：餐饮、交通">
      </div>
      <div class="form-group">
        <label>备注：</label>
        <input type="text" v-model="newBill.remark" placeholder="请输入备注">
      </div>
      <div class="form-group">
        <label>日期：</label>
        <input type="date" v-model="newBill.date">
      </div>
      <button @click="addBill" class="add-button">添加账单</button>
    </div>
    
    <!-- 账单列表 -->
    <div class="bill-list">
      <h3>账单列表</h3>
      <div v-if="loading">加载中...</div>
      <div v-else-if="bills.length === 0" class="no-data">暂无账单数据</div>
      <table v-else class="bill-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>类型</th>
            <th>金额 (元)</th>
            <th>类别</th>
            <th>备注</th>
            <th>日期</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="bill in bills" :key="bill.id" :class="{ 'income': bill.type === 'income', 'expense': bill.type === 'expense' }">
            <td>{{ bill.id }}</td>
            <td>{{ bill.type === 'income' ? '收入' : '支出' }}</td>
            <td>{{ bill.amount }}</td>
            <td>{{ bill.category }}</td>
            <td>{{ bill.remark }}</td>
            <td>{{ bill.date }}</td>
            <td>
              <button @click="deleteBill(bill.id)" class="delete-button">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- 统计信息 -->
    <div class="statistics">
      <h3>账单统计</h3>
      <div class="stat-item">
        <span>总收入：</span>
        <span class="income-text">{{ totalIncome }} 元</span>
      </div>
      <div class="stat-item">
        <span>总支出：</span>
        <span class="expense-text">{{ totalExpense }} 元</span>
      </div>
      <div class="stat-item">
        <span>结余：</span>
        <span :class="balance >= 0 ? 'income-text' : 'expense-text'">{{ balance }} 元</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BillManagement',
  data() {
    return {
      bills: [],
      loading: false,
      newBill: {
        type: 'expense',
        amount: null,
        category: '',
        remark: '',
        date: new Date().toISOString().substr(0, 10)
      }
    };
  },
  computed: {
    totalIncome() {
      return this.bills
        .filter(bill => bill.type === 'income')
        .reduce((sum, bill) => sum + bill.amount, 0);
    },
    totalExpense() {
      return this.bills
        .filter(bill => bill.type === 'expense')
        .reduce((sum, bill) => sum + bill.amount, 0);
    },
    balance() {
      return this.totalIncome - this.totalExpense;
    }
  },
  methods: {
    async fetchBills() {
      try {
        this.loading = true;
        const response = await fetch('https://m1.apifoxmock.com/m1/6488085-0-default/getBills');
        const result = await response.json();
        
        if (result.code === 200) {
          this.bills = result.data;
        } else {
          alert('获取账单失败：' + result.message);
        }
      } catch (error) {
        console.error('获取账单出错：', error);
        alert('获取账单出错，请查看控制台');
      } finally {
        this.loading = false;
      }
    },
    async addBill() {
      // 表单验证
      if (!this.newBill.amount) {
        alert('请输入金额');
        return;
      }
      if (!this.newBill.category) {
        alert('请输入类别');
        return;
      }
      if (!this.newBill.date) {
        alert('请选择日期');
        return;
      }
      
      try {
        const response = await fetch('https://m1.apifoxmock.com/m1/6488085-0-default/addBills', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.newBill)
        });
        
        const result = await response.json();
        
        if (result.code === 200) {
          alert('添加账单成功');
          // 生成一个新的ID（实际应用中应该由后端生成）
          const newId = this.bills.length > 0 ? Math.max(...this.bills.map(b => b.id)) + 1 : 1;
          
          // 将新账单添加到列表中
          this.bills.push({
            id: newId,
            ...this.newBill
          });
          
          // 重置表单
          this.newBill = {
            type: 'expense',
            amount: null,
            category: '',
            remark: '',
            date: new Date().toISOString().substr(0, 10)
          };
        } else {
          alert('添加账单失败：' + result.message);
        }
      } catch (error) {
        console.error('添加账单出错：', error);
        alert('添加账单出错，请查看控制台');
      }
    },
    async deleteBill(id) {
      if (!confirm(`确定要删除ID为 ${id} 的账单吗？`)) {
        return;
      }
      
      try {
        const response = await fetch(`https://m1.apifoxmock.com/m1/6488085-0-default/deleteBills?id=${id}`, {
          method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.code === 200) {
          alert('删除账单成功');
          // 从列表中移除该账单
          this.bills = this.bills.filter(bill => bill.id !== id);
        } else {
          alert('删除账单失败：' + result.message);
        }
      } catch (error) {
        console.error('删除账单出错：', error);
        alert('删除账单出错，请查看控制台');
      }
    }
  },
  mounted() {
    this.fetchBills();
  }
};
</script>

<style scoped>
.bill-management {
  font-family: Arial, sans-serif;
}

h2 {
  color: #333;
  margin-bottom: 20px;
}

h3 {
  color: #555;
  margin: 15px 0;
}

.form-group {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.form-group label {
  width: 60px;
  display: inline-block;
  margin-right: 10px;
}

input, select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 200px;
}

button {
  padding: 8px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.add-button {
  background-color: #4CAF50;
  color: white;
  margin-top: 10px;
}

.add-button:hover {
  background-color: #45a049;
}

.delete-button {
  background-color: #f44336;
  color: white;
  font-size: 0.8em;
}

.delete-button:hover {
  background-color: #d32f2f;
}

.add-bill-form, .bill-list, .statistics {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.bill-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 10px;
}

.bill-table th, .bill-table td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.bill-table th {
  background-color: #f2f2f2;
  font-weight: bold;
}

.bill-table tr.income {
  background-color: #e8f5e9;
}

.bill-table tr.expense {
  background-color: #ffebee;
}

.bill-table tr:hover {
  background-color: #f5f5f5;
}

.no-data {
  padding: 20px;
  text-align: center;
  color: #888;
}

.statistics .stat-item {
  margin: 10px 0;
  font-size: 1.1em;
}

.income-text {
  color: #4CAF50;
  font-weight: bold;
}

.expense-text {
  color: #f44336;
  font-weight: bold;
}
</style> 
